package com.ruoyi.coal.common.utils;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class MyByteToMessageCodec extends ByteToMessageCodec<Object> {
    private static final Logger log = LoggerFactory.getLogger(com.ruoyi.coal.common.utils.MyByteToMessageCodec.class);

    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) {
        try {
            byte[] data = getBytes(buf);
            out.add(new String(data, "GBK"));
            ctx.writeAndFlush(out);
        } catch (Exception exception) {
            log.error("读取 ByteBuf 字节内容失败");
        }
    }

    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) {
        byte[] body = (byte[])msg;
        out.writeBytes(body);
    }

    private byte[] getBytes(ByteBuf buf) {
        byte[] data = null;
        try {
            int readablebytes = buf.readableBytes();
            ByteBuf tempBuf = buf.readBytes(readablebytes);
            data = new byte[readablebytes];
            tempBuf.getBytes(0, data);
        } catch (Exception exception) {
            log.error("读取 ByteBuf 字节内容失败");
        }
        return data;
    }
}

